package com.cneport.das.server.conf;

import com.cneport.das.common.utils.FileUtil;
import com.cneport.das.common.utils.JAXBUtils;
import com.cneport.das.common.utils.StringUtil;
import com.cneport.das.server.param.conf.Permit;
import com.cneport.das.server.param.conf.ServiceUrl;
import com.cneport.das.server.trans.conf.Authen;
import com.cneport.das.server.trans.conf.Bindings;
import com.cneport.das.server.trans.conf.CorpInfo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Desc 配置缓存
 * @Ver 1.0
 * @Author GavinZhang
 * @Company 东方物通科技有限（北京）公司
 * @Date 2021-12-13 16:29:23
 */
@Configuration
@Slf4j
@Getter
public class ConfigCaches {

    @Value("${das.customer.config.basedir}")
    private String confBasePath;

    @Value("${param.server.mode}")
    private Integer mode;
    @Value("${param.server.access}")
    private Integer access;
    @Value("${param.dispatch.same}")
    private Integer same;
    @Value("${client.banding.enabled}")
    private Integer enableBinding;


    private static final String PERMIT_XML = "param-permit.xml";
    private static final String SRV_URL_XML = "param-srvUrl.xml";
    private static final String AUTHENTIC_XML = "trans-authentic.xml";
    private static final String CORP_INFO_XML = "corp-info.xml";
    private static final Map<String, CorpInfo> corpInfos = new ConcurrentHashMap<>();
    private static final Map<String, Authen> corpAuths = new ConcurrentHashMap<>();
    private static final Map<String, List<String>> copBindNums = new ConcurrentHashMap<>();
    private static final Map<String, List<Bindings.Bind>> copBinds = new ConcurrentHashMap<>();
    private static final Map<String, Permit> corpPermits = new ConcurrentHashMap<>();
    private static ServiceUrl serviceUrl;
    public static final String BINDINGS_XML = "client-bindings.xml";

    @Scheduled(cron = "0 0/3 * * * ?")
    public void refresh() {
        parse();
    }

    @PostConstruct
    public void parse() {
        if (StringUtil.isBlank(confBasePath)) {
            log.error("配置项不存在：【das.customer.config.basedir】");
            return;
        }
        if (mode == null) {
            mode = 0;
        }
        if (access == null) {
            access = 0;
        }
        if (same == null) {
            same = 0;
        }


        //以公司为单位解析配置文件
        String confBaseDir = confBasePath;
        File confDir = new File(confBaseDir);
        if (confDir == null) {
            log.error("DAS server 无相关的的配置信息");
            return;
        } else {
            //一定有，否则不会到此
            String[] dirs = confDir.list();
            if (dirs == null) {
                return;
            }
            for (String corpNo : dirs) {
                //解析配置文件 param-srvUrl.xml (全局性的)
                if (corpNo.equals(SRV_URL_XML)) {
                    String urlConfPath = confBasePath + File.separator + SRV_URL_XML;
                    File file = new File(urlConfPath);
                    if (!file.exists()) {
                        log.error("配置文件不存在：" + urlConfPath);
                        return;
                    } else {
                        String url_conf_content = FileUtil.readFile(urlConfPath);
                        serviceUrl = JAXBUtils.xml2Obj(ServiceUrl.class, url_conf_content);
                    }
                } else {
                    String corpConfDir = confBaseDir + File.separator + corpNo;
                    String auFilePath = corpConfDir + File.separator + AUTHENTIC_XML;
                    //解析trans-authentic.xml
                    File authFile = new File(auFilePath);
                    if (authFile.exists()) {
                        String auth_content = FileUtil.readFile(auFilePath);
                        if (!StringUtil.isBlank(auth_content)) {
                            Authen authen = JAXBUtils.xml2Obj(Authen.class, auth_content);
                            if (authen != null) {
                                corpAuths.put(corpNo, authen);
                            }

                        }

                    } else {
                        log.error("公司" + corpNo + " 配置文件" + AUTHENTIC_XML + "不存在！");
                    }
                    //解析corp-info.xml文件
                    String copFilePath = corpConfDir + File.separator + CORP_INFO_XML;
                    File copthFile = new File(copFilePath);
                    if (copthFile.exists()) {
                        String cop_content = FileUtil.readFile(copFilePath);
                        if (!StringUtil.isBlank(cop_content)) {
                            CorpInfo corpInfo = JAXBUtils.xml2Obj(CorpInfo.class, cop_content);
                            if (corpInfo != null) {
                                corpInfos.put(corpNo, corpInfo);
                            }

                        }

                    } else {
                        log.error("公司" + corpNo + " 配置文件" + CORP_INFO_XML + "不存在！");
                    }


                    //解析client-bindings.xml
                    String bindFilePath = corpConfDir + File.separator + BINDINGS_XML;
                    File bindFile = new File(bindFilePath);
                    if (bindFile.exists()) {
                        String bind_content = FileUtil.readFile(bindFilePath);
                        if (!StringUtil.isBlank(bind_content)) {
                            Bindings bindings = JAXBUtils.xml2Obj(Bindings.class, bind_content);
                            List<Bindings.Bind> binding = bindings.getBinding();
                            if (bindings != null && binding != null) {
                                copBinds.put(corpNo, binding);
                                List<String> bindNos = new ArrayList<>();
                                for (Bindings.Bind bd : binding) {
                                    if (bd.getIsDel() == 0) {
                                        String bindingNo = bd.getBindingNo();
                                        if (!StringUtil.isBlank(bindingNo)) {
                                            bindNos.add(bindingNo);
                                        }
                                    }
                                }
                                copBindNums.put(corpNo, bindNos);
                            }

                        }

                    } else {
                        log.info("公司" + corpNo + " 配置文件" + BINDINGS_XML + "尚不存在！");
                    }

                    //解析param-permit.xml
                    String permitFilePath = corpConfDir + File.separator + PERMIT_XML;
                    File permitFile = new File(permitFilePath);
                    if (permitFile.exists()) {
                        String permit_content = FileUtil.readFile(permitFilePath);
                        if (!StringUtil.isBlank(permit_content)) {
                            Permit permit = JAXBUtils.xml2Obj(Permit.class, permit_content);
                            if (permit != null) {
                                corpPermits.put(corpNo, permit);
                            }
                        }

                    } else {
                        log.error("公司" + corpNo + " 配置文件" + PERMIT_XML + "不存在！");
                    }
                }
            }
        }

    }


    public Map<String, List<String>> getCorpBinds() {
        return ConfigCaches.copBindNums;
    }


    public Map<String, Permit> getPermits() {
        return ConfigCaches.corpPermits;
    }

    public ServiceUrl getSRV_URL_XML() {
        return ConfigCaches.serviceUrl;
    }


    public List<String> getCorpBindNosByCorpNo(String corpNo) {
        if (StringUtil.isBlank(corpNo)) {
            return null;
        }
        return copBindNums.get(corpNo);
    }

    public List<Bindings.Bind> getCorpBindsByCorpNo(String corpNo) {
        if (StringUtil.isBlank(corpNo)) {
            return null;
        }
        return copBinds.get(corpNo);
    }

    public Authen getCorpAuthByCorpNo(String corpNo) {
        if (StringUtil.isBlank(corpNo)) {
            return null;
        }
        return corpAuths.get(corpNo);
    }

    public Map<String, Authen> getAllCorpAuth() {
        return corpAuths;
    }

    public CorpInfo getCorpInfoByCorpNo(String corpNo) {
        if (StringUtil.isBlank(corpNo)) {
            return null;
        }
        return corpInfos.get(corpNo);
    }

    public Map<String, CorpInfo> getAllCorpInfo() {
        return corpInfos;
    }
}
